﻿namespace StyleCop.CSharp
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// A helper utility for working with dictionaries.
    /// </summary>
    public static class DictionaryHelper
    {
        #region Public Methods
        /// <summary>
        /// Gets the item with the specified key if it exists, otherwise adds it.
        /// </summary>
        /// <typeparam name="TKey">The type of the key.</typeparam>
        /// <typeparam name="TItem">The type of the item.</typeparam>
        /// <param name="dictionary">The dictionary.</param>
        /// <param name="key">The key to search for.</param>
        /// <param name="itemCreator">The item creator.</param>
        /// <returns>The item with the specified key.</returns>
        public static TItem TryGetOrCreate<TKey, TItem>(this Dictionary<TKey, TItem> dictionary, TKey key, Func<TItem> itemCreator)
        {
            // Check if the key is already in the dictionary.
            TItem item;
            if (!dictionary.TryGetValue(key, out item))
            {
                // If the key isn't already in the dictionary then create its associated item and add it.
                item = itemCreator();
                dictionary.Add(key, item);
            }

            return item;
        }
        #endregion Public Methods
    }
}